//导入Ajax
import {
    ajax,
    isObject
} from "./ajax.js"
//创建全局下的对象，储存获取的数据
var bookstack = []
var typestack = [];
//判断是否有参
var value1 = unescape(window.location.href.split("?")[1])
var way = ""
var mat = ''
if(window.location.href.split("?")[1]){
    var value2 = value1.split("&")
    if(value2[1].split("=")[1].split('-')[1]&&(value2[1].split("=")[1].split('-')[0]!='smaNav')){
        way='midNav';
        if(value2[1].split("=")[1].split('-')[0]=='bigNav1'){
            if(value2[1].split("=")[1].split('-')[1]=='1'){
                mat = '床'
            }else if(value2[1].split("=")[1].split('-')[1]=='2'){
                mat = '床头柜'
            }else if(value2[1].split("=")[1].split('-')[1]=='3'){
                mat = '衣柜'
            }else if(value2[1].split("=")[1].split('-')[1]=='4'){
                mat = '梳妆台'
            }else if(value2[1].split("=")[1].split('-')[1]=='5'){
                mat = '衣帽架'
            }
        }else if(value2[1].split("=")[1].split('-')[0]=='bigNav2'){
            if(value2[1].split("=")[1].split('-')[1]=='1'){
                mat = '沙发'
            }else if(value2[1].split("=")[1].split('-')[1]=='2'){
                mat = '电视柜'
            }else if(value2[1].split("=")[1].split('-')[1]=='3'){
                mat = '茶几'
            }else if(value2[1].split("=")[1].split('-')[1]=='4'){
                mat = '酒柜'
            }else if(value2[1].split("=")[1].split('-')[1]=='5'){
                mat = '鞋柜'
            }else if(value2[1].split("=")[1].split('-')[1]=='6'){
                mat = '休闲椅'
            }else if(value2[1].split("=")[1].split('-')[1]=='7'){
                mat = '屏风'
            }
        }else if(value2[1].split("=")[1].split('-')[0]=='bigNav3'){
            if(value2[1].split("=")[1].split('-')[1]=='1'){
                mat = '餐桌'
            }else if(value2[1].split("=")[1].split('-')[1]=='2'){
                mat = '餐椅'
            }else if(value2[1].split("=")[1].split('-')[1]=='3'){
                mat = '餐边柜'
            }
        }else if(value2[1].split("=")[1].split('-')[0]=='bigNav4'){
            if(value2[1].split("=")[1].split('-')[1]=='1'){
                mat = '书桌'
            }else if(value2[1].split("=")[1].split('-')[1]=='2'){
                mat = '书架'
            }else if(value2[1].split("=")[1].split('-')[1]=='3'){
                mat = '书椅'
            }
        }else if(value2[1].split("=")[1].split('-')[0]=='bigNav5'){
            if(value2[1].split("=")[1].split('-')[1]=='1'){
                mat = '儿童床'
            }else if(value2[1].split("=")[1].split('-')[1]=='2'){
                mat = '儿童床头柜'
            }else if(value2[1].split("=")[1].split('-')[1]=='3'){
                mat = '儿童桌'
            }else if(value2[1].split("=")[1].split('-')[1]=='4'){
                mat = '儿童衣柜'
            }
        }else if(value2[1].split("=")[1].split('-')[0]=='bigNav6'){
            if(value2[1].split("=")[1].split('-')[1]=='1'){
                mat = '办公桌'
            }else if(value2[1].split("=")[1].split('-')[1]=='2'){
                mat = '办公椅'
            }else if(value2[1].split("=")[1].split('-')[1]=='3'){
                mat = '文件柜'
            }else if(value2[1].split("=")[1].split('-')[1]=='4'){
                mat = '办公沙发'
            }
        }
    }else if(value2[1].split("=")[1].split('-')[1]&&(value2[1].split("=")[1].split('-')[0]=='smaNav')){
        way ='smaNav'
        mat = unescape(value2[1].split("=")[1].split('-')[1])
    }else{
        way = value2[1].split("=")[1]
    }
}else{
    way = "all"
}

new Promise(function(resolve, reject){
//调用ajax，获取搜索出的数据******************************
ajax({
    url: "./php/search.php",
    dataType: "json",
    data:  {ways:way,mid:mat},
    type: "get",
    cache: false,
    //调用成功执行函数
    success: function (data) {
        //声明对象储存需要的数据
        var obj = {};
        //计数
        var j = 0;
        //判断是否需要break
        var twenty = false;

        //way = "all"时
        //搜索出的书
        var str = ""
        // for(var i=0;i<20;i++){
        //     str +=`
        //     <div class="daytabs-main-box">
        //     <div class="daytabs-main">
        //         <a href="./detail.html?bname=${escape(data[i]['id'])}" >
        //             <img src=${data[i]["url"]} alt="">
        //         </a>
        //         <a href="./detail.html?bname=${escape(data[i]['id'])}">
        //         <p class="bookname">${data[i]['goodsname']}</p>
        //         </a>
        //         <div class="daytabs-price">
        //             <span class="daytabs-p">
        //             ${data[i]['price2']}
        //             </span>
        //             <span class="daytabs-n">
        //             ${data[i]['price1']}
        //             </span>
        //         </div>
        //         <p class="author">${data[i]['shop']}</p>
        //     </div>
        // </div>
        //     `
        // }
        bookstack = data
        typestack = data
        // $(".left-main").html(str)
        resolve()

    },
    error: function (x) {
        alert(x)
    }
})
})
.then(()=>{
    // 进入当前页面加载第一页数据
    getPageData(current,size)
})
//调用ajax，获取搜索出的数据******************************

//给按价格排序下的a标签添加点击事件******************
$(".pand-second a").on("click",function (e){
    //事件对象
    var e = e || window.event;
    //事件目标
    var target = e.target || e.srcElement;
    //价格范围
    var pricearr = [0,99999];
    var str = ""
    if(target.innerHTML=="价格"){
        pricearr = [0,99999]
    }else if(target.innerHTML=="0-99元"){
        pricearr = [0,99]
    }else if(target.innerHTML=="100-299元"){
        pricearr = [100,299]
    }else if(target.innerHTML=="300-499元"){
        pricearr = [300,499]
    }else if(target.innerHTML=="500-999元"){
        pricearr = [500,999]
    }else if(target.innerHTML=="1000元以上"){
        pricearr = [1000,99999]
    }else if(target.innerHTML=="不限"){
        pricearr = [0,99999]
    }
    typestack = []
    for(var i=0;i<bookstack.length-1;i++){
        var com = bookstack[i]['price2'].split('￥')[1]
        if(com>=pricearr[0]&&com<=pricearr[1]){
            typestack.push(bookstack[i])
        }
    }
    if(typestack[0]){
        var page = 1
        var size = 12;
        getPageData(page,size)
    }else{
        
        str = "<h2 class='donot'> 不存在您选取的商品</h2>"
        getPageData(page,size)
        $(".left-main").html(str)
    }
    return false
})
$(".sort-item a").on("click",function (e){
    //事件对象
    var e = e || window.event;
    //事件目标
    var target = e.target || e.srcElement;
    //价格数组
    var pricearr = [];
    if(target.innerHTML=="综合排序"||target.innerHTML=="销量"){
        var page = 1
        var size = 12;
        getPageData(page,size)
    }else if(target.innerHTML=="价格"){
    //遍历获取的数据
    for(var i = 0;i<typestack.length;i++){
        pricearr.push(typestack[i])
        pricearr[i]['compare'] = typestack[i]['price2'].split('￥')[1]
    }
    function compare(p){ //这是比较函数
        return function(m,n){
            var a = m[p];
            var b = n[p];
            return a - b; //升序
        }
    }
    // 排序
    pricearr.sort(compare("compare"))
    typestack = pricearr
    var page = 1
    var size = 12;
    getPageData(page,size)
    }

    return false
})

//给按价格排序下的a标签添加点击事件******************

//取消引入的滚动条事件
window.onload = null






let count = 0 // 数据总条数
let pages = 0 // 数据总页数
let current = 1 // 当前页码
let size = 12 // 每页条数



function getPageData(page,size){//获取分页数据
	// $.ajax({
	// 	url: "./php/search.php",
	// 	type: 'post',
	// 	data: {
	// 		page: page,
	// 		size: size,
    //         ways:way
	// 	},
	// 	dataType: 'json',
	// 	success: function (data){
				count = typestack.length
				pages = Math.ceil(typestack.length/size)
                var dataarr = [];
                for(var j = (page-1)*size;j<((page-1)*size+size);j++){
                    if(typestack[j]){
                        dataarr.push(typestack[j])
                    }else{
                        break;
                    }
                }
				// 根据数据渲染页面
				renderTable(dataarr)
				// 渲染分页
				renderPage(current,pages)
                $('.find b').html(count)
				// 显示总条数
				// $('.number').text(count)


	// 	}
	// })
}

function renderTable(data){//渲染页面
	let str = ''
	$.each(data,function (index,item){
        str +=`
        <div class="daytabs-main-box">
        <div class="daytabs-main">
            <a href="./detail.html?bname=${escape(data[index]['id'])}" >
                <img src=${data[index]["url"]} alt="">
            </a>
            <a href="./detail.html?bname=${escape(data[index]['id'])}">
            <p class="bookname">${data[index]['goodsname']}</p>
            </a>
            <div class="daytabs-price">
                <span class="daytabs-p">
                ${data[index]['price2']}
                </span>
                <span class="daytabs-n">
                ${data[index]['price1']}
                </span>
            </div>
            <p class="author">${data[index]['shop']}</p>
        </div>
    </div>
        `
	})
	$(".left-main").html(str)
}

function renderPage(current,page){// 渲染分页
	var str = ''
    if(page<=8){
        for (var i = 1; i <= page; i++){
            str += '<i>'+i+'</i>'
        }
    }else if(page>8&&(current>4&&current<page-3)){
        for (var i = 1; i <= 2; i++){
            str += '<i>'+i+'</i>'
        }
        str += '<i>'+'...'+'</i>'
        for (var i = parseInt(current)-1; i<= parseInt(current)+1; i++){
            str += '<i>'+i+'</i>'
        }
        str += '<i>'+'...'+'</i>'
        for (var i = page-1; i <= page; i++){
            str += '<i>'+i+'</i>'
        }
    }else if(page>8&&(current<4)){
        for (var i = 1; i <= 4; i++){
            str += '<i>'+i+'</i>'
        }
        str += '<i>'+'...'+'</i>'
        for (var i = page-1; i <= page; i++){
            str += '<i>'+i+'</i>'
        }
    }else if(page>8&&(current==4)){
        for (var i = 1; i <= 5; i++){
            str += '<i>'+i+'</i>'
        }
        str += '<i>'+'...'+'</i>'
        for (var i = page-1; i <= page; i++){
            str += '<i>'+i+'</i>'
        }
    }else if(page>8&&(current==page-3)){
        for (var i = 1; i <= 2; i++){
            str += '<i>'+i+'</i>'
        }
        str += '<i>'+'...'+'</i>'
        for (var i = page-4; i <= page; i++){
            str += '<i>'+i+'</i>'
        }
    }
    else if(page>8&&(current>page-3)){
        for (var i = 1; i <= 2; i++){
            str += '<i>'+i+'</i>'
        }
        str += '<i>'+'...'+'</i>'
        for (var i = page-3; i <= page; i++){
            str += '<i>'+i+'</i>'
        }
    }
	$('.nums').html(str)
    if(current>=5&&current<page-2&&page>8){
        $('.nums i').eq(4).addClass('active')
    }else if(current>=page-2&&page>8){
        $('.nums i').eq(7-(page-current+1)).addClass('active').siblings().removeClass('active')
    }else{
        $('.nums i').eq(current-1).addClass('active').siblings().removeClass('active')
    }
	
}

// 点击上一页
$('.prev').click(function (){
	current--
	if (current <= 0) {
		current = 1
		return
	}
	getPageData(current,size)
    if(current>=5){

    }else{
        $('.nums i').eq(current-1).addClass('active').siblings().removeClass('active')
    }
})

// 点击下一页
$('.next').click(function (){
	current++
	if (current > pages) {
		current = pages
		return
	}
	getPageData(current,size)
    if(current>=5){

    }else{
        $('.nums i').eq(current-1).addClass('active').siblings().removeClass('active')
    }
    

	
})

// 点击页码
$('.nums').on('click','i',function (){
	current = $(this).text()
	getPageData(current,size)
    if(current>=5){

    }else{
        $('.nums i').eq(current-1).addClass('active').siblings().removeClass('active')
    }
})

// 跳转到指定页
$('.go em').click(function (){
	current = $('.ipt').val()
	getPageData(current,size)
    if(current>=5){

    }else{
        $('.nums i').eq(current-1).addClass('active').siblings().removeClass('active')
    }
})
var getCookie = function getCookie(key) {
    var arr1 = document.cookie.split('; ')
    //["user1=111asdasd", "user2=222gfhft", "user3=333wwwaa"]
    for (var i = 0; i < arr1.length; i++) {
        var arr2 = arr1[i].split('=') //['user1','111asdasd']
        if (arr2[0] === key) {
            // 对数据进行解码并返回
            return unescape(arr2[1])
        }
    }
    return null
}
window.onload = function(){
        //判断是否登录成功
        if(getCookie("username")&&getCookie("loginsucess")=="true"){
            var str =`
            <p class="logingo">您好，${getCookie("username")} &nbsp;&nbsp;&nbsp;&nbsp; <a href="./index.html">【退出登录】</a> </p>
            `
            $(".loginArea .logingo").html(str)
            $(".loginArea .logingo a").on("click",function(){
                document.cookie="loginsucess=false";
            })
        }
}